#include "stdio.h"
#include "stdlib.h"

#include "DataElement.h"
#include "CircularLinkList.h"


/**
 *  循环链表初始化
 * @param clList
 * @param dataArray
 * @param length
 */
void InitCircularLinkList(CircularLinkList *clList, ElementType *dataArray, int length) {
    for (int i = 0; i < length; i++) {
        InsertCircularLinkList(clList, i + 1, dataArray[i]);
    }
}


/**
 * 在循环链表指定位置插入元素
 * @param clList 要执行操作的循环链表
 * @param position 指定位置
 * @param element 要操作的元素
 */
void InsertCircularLinkList(CircularLinkList *clList, int position, ElementType element) {
    /* 创建一个空节点 */
    CircularNode *node = (CircularNode *) malloc(sizeof(CircularNode));
    node->data = element;
    node->next = NULL;
    if (position == 1) {
        node->next = clList->next;
        if (!node->next) {
            node->next = node;
        } else {
            CircularNode *lastNode = clList->next;
            for (int i = 1; i < clList->length; i++) {
                lastNode = lastNode->next;
            }
            lastNode->next = node;
        }
        clList->next = node;
        clList->length++;
        return;
    }
    /* 插入的不是第一个节点 */
    CircularNode *currNode = clList->next;
    for (int i = 1; currNode && i < position - 1; i++) {
        currNode = currNode->next;
    }
    if (currNode) {
        node->next = currNode->next;
        currNode->next = node;
        clList->length++;
        if (position == clList->length) {
            node->next = clList->next;
        }
    }
}

void PrintCircularLinkList(CircularLinkList *clList) {
    if (clList->length == 0 || !clList->next) {
        printf("链表长度为空,没有内容可以打印!");
        clList->length = 0;
        return;
    }
    CircularNode *node = clList->next;
    for (int i = 0; i < clList->length; i++) {
        printf("%d\t%s", node->data.id, node->data.name);
        node = node->next;
        printf("\n");
    }

}


